#filename: ical.py

from icalendar import Calendar, Event
from datetime import datetime, timedelta
import re

cal = Calendar.from_string(open('basic.ics','rb').read())

tags = {'sleep':timedelta(0),
'eat':timedelta(0),
'work':timedelta(0),
'study':timedelta(0),
'net':timedelta(0),
'idle':timedelta(0),
'traffic':timedelta(0),
'life':timedelta(0),
'wash':timedelta(0)}

for envent in cal.walk('vevent'):
    # data fetch and decoding
    title = envent['SUMMARY']
    tag = envent['DESCRIPTION']
    t_begin = envent.decoded('DTSTART')
    t_end = envent.decoded('DTEND')
    t_delta = t_end - t_begin

    # statistic 
    for tag in tags:
        reg = re.compile('\[\w*'+tag+'\w*\]\w*')
        if reg.match(title):
            tags[tag] += t_delta

# Analysis
print "Analysis Result:"
print "%20s%20s\t\t%10s" %('Item', 'Time', 'Percentage')
for tag in tags:
    time = tags[tag].seconds + 86400.0 * tags[tag].days
    print "%20s%20s\t\t%10.2f" %(tag, tags[tag], time/86400.0)
